<script setup>
import {onMounted, reactive} from "vue";
import {
  addAuditService,
  deleteAuditBatchService,
  deleteAuditService,
  getAuditListService,
  updateAuditService
} from '../api/audit.js'
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  user: {},
  title: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  selectedRows: [],
  dialogVisible: false,
  dialogTitle: '',
  auditForm: {}
})

const userData = localStorage.getItem('user');
const parsedUser = (typeof userData === 'string') ? JSON.parse(userData) : userData || {};
data.user = parsedUser;

const AuditList = async () => {
  const res = await getAuditListService({
    title: data.title,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  })
  data.tableData = res.data.data.list
  data.total = res.data.data.total
}

onMounted(async () => {
  await AuditList()
})


// 表格行数据
const handleSelectionChange = (val) => {
  data.selectedRows = val
}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  data.pageSize = newSize;
  ArticleList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  data.pageNum = newPage;
  ArticleList();
};

// 重置
const refresh = async () => {
  data.title = ''
  await AuditList()
}

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 返回状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝'
  };
  return statusMap[status] || '未知状态';
};

const showUpdateDialog = (row) => {
  data.auditForm = {
    id: row.id,
    title: row.title,
    publisher: row.publisher,
    publishTime: formatDate(row.publishTime),
    status: row.status,
    content: row.content
  }
  data.dialogTitle = '修改审核'
  data.dialogVisible = true
}

const handleAuditAdd = () => {
  data.auditForm = {
    title: '',
    content: ''
  }
  data.dialogTitle = '新增审核'
  data.dialogVisible = true
}

const handleSaveAudit = async () => {
  if (data.auditForm.id) {
    const res = await updateAuditService(data.auditForm)
    if (res.data.code === '200') {
      await AuditList()
      data.dialogVisible = false
      ElMessage.success("修改成功")
    } else {
      ElMessage.error(res.data.message)
    }
  } else {
    const res = await addAuditService(data.auditForm)
    if (res.data.code === '200') {
      await AuditList()
      data.dialogVisible = false
      ElMessage.success("新增成功")
    } else {
      ElMessage.error(res.data.message)
    }
  }
}

// 删除审核
const deleteHandle = async (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前审核，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteAuditService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await AuditList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

// 批量删除
const handleDeleteBatch = async () => {

  if (!data.selectedRows || data.selectedRows.length === 0) {
    ElMessage.warning("请先选择要删除的审核");
    return;
  }

  const ids = data.selectedRows.map(item => item.id)

  ElMessageBox.confirm(
      '当前操作将永久删除选中的审核，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteAuditBatchService(ids);
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await AuditList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  });
}
</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="data.title" clearable style="width: 240px" placeholder="请输入标题"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="AuditList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" v-if="data.user.userType === '1'" style="margin-left: 0" icon="DocumentAdd"
                 @click="handleAuditAdd">新增审核
      </el-button>
      <el-button type="danger" v-if="data.user.userType === '1'" style="margin-left: 0" icon="Delete"
                 @click="handleDeleteBatch">批量删除
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="data.tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="title" align="center" label="审核标题"/>
        <el-table-column prop="content" align="center" label="审核说明"/>
        <el-table-column prop="publisher" align="center" label="发布人"/>
        <el-table-column align="center" label="发布时间">
          <template #default="scope">
            <el-text type="info">{{ formatDate(scope.row.publishTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" label="审核状态">
          <template #default="scope">
            <el-text v-if="scope.row.status === 0" type="warning">{{ getStatusText(scope.row.status) }}</el-text>
            <el-text v-if="scope.row.status === 1" type="success">{{ getStatusText(scope.row.status) }}</el-text>
            <el-text v-if="scope.row.status === 2" type="danger">{{ getStatusText(scope.row.status) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="reason" align="center" label="审核信息"/>
        <el-table-column align="center" label="操作" width="200">
          <template #default="scope">
            <el-button :disabled="scope.row.status === 1 || scope.row.status === 2" type="primary"
                       v-if="data.user.userType === '1'" @click="showUpdateDialog(scope.row)"
                       icon="Edit">修改
            </el-button>
            <el-button type="danger"
                       v-if="data.user.userType === '1'" icon="Delete"
                       @click="deleteHandle(scope.row.id)">删除
            </el-button>
            <el-button :disabled="scope.row.status === 1 || scope.row.status === 2" type="primary"
                       v-if="data.user.userType === '0'" @click="showUpdateDialog(scope.row)"
                       icon="Edit">审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <!-- 新增 / 修改 -->
  <el-dialog v-model="data.dialogVisible" :title="data.dialogTitle" align-center width="450" destroy-on-close>
    <el-form :model="data.auditForm" :rules="rules" ref="formRef" label-width="80px"
             style="padding: 0 50px 0 0">
      <el-form-item label="审核标题" class="el-form-item">
        <el-input v-if="data.user.userType === '1'" v-model="data.auditForm.title" placeholder="请输入标题"/>
        <el-input disabled v-else v-model="data.auditForm.title" placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item label="审核说明" class="el-form-item">
        <el-input v-if="data.user.userType === '1'" :rows="6" type="textarea" v-model="data.auditForm.content"
                  placeholder="请输入说明"/>
        <el-input disabled v-else v-model="data.auditForm.content" :rows="6" type="textarea" placeholder="请输入说明"/>
      </el-form-item>
      <el-form-item v-if="data.user.userType === '0'" label="审核状态" prop="status" class="el-form-item">
        <el-radio-group v-model="data.auditForm.status">
          <el-radio value="1" size="large" border>审核通过</el-radio>
          <el-radio value="2" size="large" border>审核拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="data.user.userType === '0' && data.auditForm.status === '2'" label="拒绝理由"
                    class="el-form-item">
        <el-input :rows="6" type="textarea" v-model="data.auditForm.reason"
                  placeholder="请输入拒绝理由"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="data.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveAudit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep() .el-radio-group {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}
</style>